<?php
/* 签到抽奖类 */
namespace Api\Controller;
use Think\Controller;
use Think\Log;
class RushBuyController extends Controller {

	protected $openid = 0;  //用户ID
 	protected $sex = -1;
 	protected $nickname = '';
 	//protected $appId = 'wx3a359484b1476dce';
 	//protected $appSecret = 'dcfc63d36a17561c8bef74961685fc57';
 	protected $appId = 'wxdee468b712ebc4ca';
 	protected $appSecret = '8bf035a8c677142e5b105c4bd3ad0f28';

// 	protected $appId = 'wx329ba4a4a87185e0';
// 	protected $appSecret = '4da9c87c7fb436f787a06b0537041103';
 	protected $accountArr = array(62179101,62179201,62139001,62179301,62179501,
								  62179601,62252101,62252201,62135101,62135201,
								  62252301,62251601,62251801,62251701,62251901,
								  62252001,62252301,98430301,98430101);//,8430101);

 	protected $url = 'http://demo.lanyipp.com/devzhaoshifu/rush/index.html';
 	
	public function __construct()
	{
		//解决跨域
		echoHeader();
		// if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === false ) {
		// 	echo '请在微信浏览器打开';exit;
		// 	$this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'请在微信浏览器打开'));
		// }
		//判断是否微信访问
		// if(isset($_SESSION['wxuserinfo'])){
		// 	$userinfo = $_SESSION['wxuserinfo'];
		// 	// if($userinfo['openid'] == 'o8acBs5q0i7zdOekAl7u4HB81D-A'){
		// 	// 	unset($userinfo['openid']);
		// 	// }
		// 	$this->sex = $userinfo['sex'];
		// 	$this->nickname = $userinfo['nickname'];
		// }else{
		// 	$userinfo = array();
		// }

		// //Log::write(var_export($userinfo, true),'openid');
		// if (isset($userinfo['openid'])) {
		// 	$this->openid = $userinfo['openid'];
		// }
		// $jump = I('param.jump', 0 , 'intval');
		// if (!$this->openid and $jump) {
		// 	$this->wxauth();
		// }
	}

	public function wxauth()
	{
		$url = 'http://demo.lanyipp.com/devzhaoshifu/api.php/RushBuy/setUser';
		//$url = 'http://119.29.169.29/devzhaoshifu/api.php/RushBuy/setUser';
		$jump = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=';
		$jump .= $this->appId.'&redirect_uri='.urlencode($url);
		$jump .= '&response_type=code&scope=snsapi_userinfo#wechat_redirect';
		header("Location:".$jump);
		exit;
	}

	public function setUser(){
		$code = I('param.code', '', 'trim');
    	$rand = rand(1,100000);
    	if ($code) {
    		$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appId.'&secret='.$this->appSecret.'&code='.$code.'&grant_type=authorization_code';

    		$res = $this->setUserInfo($url);
    		if($res){
    			header("Location:".$this->url."?v=".$rand);
    		}
		}else{
			header("Location:".$this->url."?v=".$rand);
		}
	}
    //首页
    public function index()
    {
    	if(IS_POST){
	    	$res = array();
	    	$res['err_code'] = 200;
	    	$data['prize'] = $this->getPrize();
	    	
	    	$account = isset($_SESSION['account']) ? $_SESSION['account'] : '';
	    	$phone = isset($_SESSION['phone']) ? $_SESSION['phone'] : '';
	    	foreach($data['prize'] as $k => $v){
	    		$data['prize'][$k]['is_buy'] = $this->isBuy($account, $v['activity_id'], $v['prize_id']);
	    	}

		    $isBind  = ($account and $phone) ? true : false;
    		$data['is_bind'] = $isBind;
    		$data['phone'] = $phone;
    		$data['account'] = $account;
	    	
	    	$res['err_msg'] = $data;
	    	$this->ajaxReturn($res, 'JSON');
    	}else{
    		$rand = rand(1,100000);
    		header("Location:".$this->url."?v=".$rand);
    	}
	}

	public function info()
	{
		$map['id'] = I('post.activity_id', 0, 'intval');
		$map['is_deleted'] = 0;
		$model = M('RushBuy');

		$info = $model->where($map)->find();
		if (!$info) {
			$this->ajaxReturn(array("err_code"=>100001, 'err_msg'=>'活动不存在'));
		}
		$info['description'] = htmlspecialchars_decode($info['description']);
 		$info['start_time'] = date('Y-m-d H:i:s', $info['start_time']);
		$info['end_time'] = date('Y-m-d H:i:s', $info['end_time']);
		$this->ajaxReturn(array('err_code'=>200,'err_msg'=>$info));
	}


	public function buy()
	{
		$data['activity_id'] = I('post.activity_id', 0, 'intval');
		$data['nickname'] = I('post.name', '', 'trim');
		$data['phone'] = I('post.phone', '', 'trim');
		$data['account'] = I('post.account', '', 'trim');
	
		if (empty($data['nickname'])) {
			$this->ajaxReturn(array('err_code'=>10007,'err_msg'=>'请输入您的姓名！'));
		}
		if (!is_numeric($data['phone']) or strlen($data['phone']) != 11) {
			$this->ajaxReturn(array('err_code'=>10004,'err_msg'=>'请输入正确的手机号码！'));
		}
		if (!is_numeric($data['account'])){
			$this->ajaxReturn(array('err_code'=>10005,'err_msg'=>'请输入正确的卡号！'));
		}
		//验证卡号长度与前缀
		$len = strlen($data['account']);
		if ($len < 8) {
			$this->ajaxReturn(array('err_code'=>10006,'err_msg'=>'请输入正确的卡号！'));
		}
		$seven = substr($data['account'], 0, 7);
		$eight = substr($data['account'], 0, 8);
		if (!in_array($eight, $this->accountArr) and $seven != 8430101) {
			$this->ajaxReturn(array('err_code'=>10006,'err_msg'=>'请输入正确的卡号！'));
		}
		if ($len == 16) {
			if(!in_array($eight, $this->accountArr)){
				$this->ajaxReturn(array('err_code'=>10006,'err_msg'=>'请输入正确的卡号！'));
			}
		}elseif($len == 15){
			if($account != 8430101){
				$this->ajaxReturn(array('err_code'=>10006,'err_msg'=>'请输入正确的卡号！'));
			}
		}else{
			$this->ajaxReturn(array('err_code'=>10006,'err_msg'=>'请输入正确的卡号！'));
		}
		//to do 验证
		// $prizeArr = $this->getPrize();
		// $prize = array();
		// //Log::write(var_export($data, true),'info');
		// //Log::write(var_export($prizeArr, true), 'prize');
		// //是否还有奖品
		// foreach ($prizeArr as $k => $v) {
		// 	if($v['activity_id'] == $data['activity_id']){
		// 		$prize = $v;
		// 		break;
		// 	}
		// }
		$where['id'] = $data['activity_id'];
		$where['is_deleted'] = 0;
		$prize = M('RushBuy')->where($where)->find();

		if (!$prize) {
			$this->ajaxReturn(array('err_code'=>20005, 'err_msg'=>'活动信息错误'));

		}
		if(time() < $prize['start_time']){
			$this->ajaxReturn(array('err_code'=>20003, 'err_msg'=>'活动尚未开始哦～'));
		}
		if($rec = $this->isBuy($data['account'],$data['activity_id'],$data['phone'])){
			//如果用户名与账号跟中奖记录不一致
			if($rec['nickname'] != $data['nickname']){
				$this->ajaxReturn(array('err_code'=>20006, 'err_msg'=>'用户信息错误～'));
			}
			if($rec['account'] != $data['account']){
				$this->ajaxReturn(array('err_code'=>20007, 'err_msg'=>'用户信息错误～'));
			}
			//$model->commit();
			$nickname = $data['nickname'];
			$prizeName = $prize['prize_name'];
			$coupon = $rec['coupon'];
			$link = $prize['link'];
			$time = date("Y-m-d", $rec['add_time']);
			//$msg = '恭喜您！抢兑成功，用户姓名：'.$data['nickname'].'，商品名称：'.$prize['prize_name'].' '. $rec['coupon'].'，使用网站：http://www.travelzoo.com/cn/local-deals/a-1025/Shanghai/deals。若兑换过程中由于支付操作失误出现折扣码失效情况，可于24小时之后再次登陆兑换。如在兑换过程中出现任何问题，请及时联系旅游族，客服热线：400-801-3388,谢谢！[浦发银行上海分行]';
			$this->ajaxReturn(array('err_code'=>200,'nickname'=>$nickname,'prize'=>$prizeName, 'coupon'=>$coupon, 'link'=>$link, 'time'=>$time));			
		}
		
		if(time() > $prize['end_time']){
			$this->ajaxReturn(array('err_code'=>20004, 'err_msg'=>'活动已经结束啦～'));
		}
		// if ($prize['num'] <= 0) {
		// 	$this->ajaxReturn(array('err_code'=>20001, 'err_msg'=>'您来迟一步了～奖品已被抢光！'));
		// }
		
		
		$map['rush_id'] = $data['activity_id'];
		$map['is_used'] = 0;
		$map['is_deleted'] = 0;
		$coupon = M('RushBuyCoupon')->where($map)->find();
		if (!$coupon) {
			$this->ajaxReturn(array('err_code'=>20001, 'err_msg'=>'您来迟一步了～奖品已被抢光！'));
		}
		$data['coupon'] = $coupon['coupon'];
		$data['add_time'] = time();

		$model = M('RushBuyRecord');
		$model->startTrans();
		$res = $model->add($data);
		if($res){
			$update = M('RushBuyCoupon')->where(array('id'=>$coupon['id']))->save(array('is_used'=>1));
			if ($update) {
				$model->commit();
				$nickname = $data['nickname'];
				$link = $prize['link'];
				$prizeName = $prize['prize_name'];
				$coupon = $coupon['coupon'];
				$this->ajaxReturn(array('err_code'=>200,'nickname'=>$nickname,'prize'=>$prizeName, 'coupon'=>$coupon,'link'=>$link, 'time'=>date('Y-m-d')));

			}else{
				$model->rollback();
				$this->ajaxReturn(array('err_code'=>1001,'err_msg'=>'系统繁忙，请稍后再操作'));
			}
		}else{
			$model->rollback();
			$this->ajaxReturn(array('err_code'=>1001,'err_msg'=>'系统繁忙，请稍后再操作'));
		}
		//减少奖品库存
		// foreach ($prize as $k => $v) {
		// 	if ($v['prize_id'] == $data['prize_id']) {
		// 		$prize[$k]['num'] = $v['num'] - 1;
		// 	}
		// }

		// S(array('type'=>'redis','expire'=>86400*30));
  //       $key = '__ANOTHER_PRIZE__';
  //       S($key, $prize);

  //       $index = $data['account'].'_'.$data['activity_id'].'_'.$data['prize_id'];
        
  //       S(array('type'=>'redis'));
  //       $key = '__RUSH_BUY_DATA__';
  //       $buyData = S($key);
  //       $buyData[$index] = $data;
        
  //       S(array('type'=>'redis','expire'=>86400*30));
  //       S($key, $buyData);
  //       if(count($buyData) >= 100){
  //       	$this->insert();
  //       }
  //       $_SESSION['account'] = $data['account'];
  //       $_SESSION['phone'] = $data['phone'];
//		$model->add($data);
        $msg = '恭喜您！抢兑成功，用户姓名：'.$data['nickname'].'，商品名称：Travelzoo价值150元折扣码 123456，使用网站：http://www.travelzoo.com/cn/local-deals/a-1025/Shanghai/deals。若兑换过程中由于支付操作失误出现折扣码失效情况，可于24小时之后再次登陆兑换。如在兑换过程中出现任何问题，请及时联系旅游族，客服热线：400-801-3388,谢谢！[浦发银行上海分行]';
		$this->ajaxReturn(array('err_code'=>200,'err_msg'=>$msg));
	}

	private function setUserInfo($url)
	{
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_HEADER,0);
 		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		$res = curl_exec($ch);
		curl_close($ch);
		$json_obj = json_decode($res,true);
		//Log::write(var_export($json_obj, true), 'json');
		//根据openid和access_token查询用户信息
		if(isset($json_obj['errcode'])){
			return false;
		}
		$access_token = $json_obj['access_token'];
		$openid = $json_obj['openid'];
		$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
		curl_setopt($ch,CURLOPT_HEADER,0);
		 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		$res = curl_exec($ch);
		curl_close($ch); //解析json 
		$user = json_decode($res,true);
		//Log::write(var_export($user,true), 'user');
		if (isset($user['openid'])) {
			$_SESSION['wxuserinfo'] = $user;
	    	return true;
		}else{
			return false;
		}
	}
	
	public function insert()
	{
		S(array('type'=>'redis'));
        $key = '__RUSH_BUY_DATA__';

        $buyData = S($key);
        if (!$buyData or empty($buyData)) {
        	return false;
        }
        $model = M('RushBuyRecord');
        $dataList = array();
        $i = 0;
        foreach ($buyData as $k => $v) {
        	if($i < 100){
        		$i++;
	        	$dataList[] = $v;
	        	unset($buyData[$k]);
        	}else{
        		break;
        	}
        }
        $res = $model->addAll($dataList, array(), true);
        if ($res) {
        	S(array('type'=>'redis','expire'=>86400*30));
        	//$buyData = array_merge($buyData);
        	S($key, $buyData);
        }
	}

	

	private function isBuy($account, $actId, $phone = '')
	{
        //数据库中是否有数据
		$model = M('RushBuyRecord');
		//20170511修改，查中奖记录以手机号码为准，不查账号
		//$map['account'] = $account;
		$map['is_deleted'] = 0;
		$map['activity_id'] = $actId;
		$map['phone'] = $phone;
		//$map['prize_id'] = $prizeId;
		$info = $model->where($map)->find();
		if ($info) {
			return $info;
		}
		return false;
		
	}
	//获取奖品
	private function getPrize()
	{
		// S(array('type'=>'redis'));
		// $key = '__ANOTHER_PRIZE__';
		// if ($data = S($key)) {
		// 	return $data;
		// }

		// $field['id'] = 'activity_id';
		// $field['prize_id'] = 1;
		// $field['title'] = 'title';
		// $field['']
		$map['is_deleted'] = 0;
		$data = M('RushBuy')->where($map)->limit(2)->select();

		foreach ($data as $k => $v) {
			$data[$k]['activity_id'] = $v['id'];
			$data[$k]['prize_id'] = 1;
			$map['rush_id'] = $v['id'];
			$map['is_used'] = 0;
			$data[$k]['num'] = M('RushBuyCoupon')->where($map)->count();
		}

		// $data[] = array(
  //   		'activity_id'=>1,
  //   		'prize_id'=>1,
  //   		'logo'=>'http://img04.tooopen.com/images/20130701/tooopen_20083555.jpg',
  //   		'title'=>'快点来抢购',
  //   		'sub_title'=>'每周四早上10:00起抢',
  //   		'prize_name'=>'三星Note7',
  //   		'price'=>'2000',
  //   		'num'=>1000,
  //   		);	
  //   	$data[] = array(
  //   		'activity_id'=>1,
  //   		'prize_id'=>2,
  //   		'logo'=>'http://img04.tooopen.com/images/20130701/tooopen_20083555.jpg',
  //   		'title'=>'快点来抢购',
  //   		'sub_title'=>'每周四早上10:00起抢',
  //   		'prize_name'=>'四星Note7',
  //   		'price'=>'1000',
  //   		'num'=>10000,
  //   		);
    //	S(array('type'=>'redis','expire'=>86400*30));
     //   $key = '__ANOTHER_PRIZE__';
     //   S($key, $data);
    	return $data;
	}
	
}